package com.cineplanet.dew.dao;

import java.util.ArrayList;
import java.util.List;

import javax.sql.DataSource;

import org.springframework.orm.hibernate3.support.HibernateDaoSupport;

import com.cineplanet.dew.exception.DAOExcepcion;
import com.cineplanet.dew.modelo.Cine;

public class CineDAOImpl extends HibernateDaoSupport implements CineDAO {
	
	private DataSource dataSource;

	public void setDataSource(DataSource dataSource) {
		this.dataSource = dataSource;
	}
	
	@Override
	public List<Cine> listar() throws DAOExcepcion {
		List<Cine> arreglo = new ArrayList<Cine>();
		try {
			arreglo = getHibernateTemplate().find("from Cine");
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		return arreglo;
	}

	@Override
	public List<Cine> cinesPorPela(int idPelicula) throws DAOExcepcion {
		List<Cine> arreglo = new ArrayList<Cine>();
		
		try {
			arreglo = getHibernateTemplate().find("select ci from Cine ci, PeliculasPorCine pc " +
										"where ci.idCine = pc.cine.idCine " +
										"and pc.pelicula.idPelicula = ?", idPelicula);
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		
		return arreglo;
	}

	@Override
	public Cine insertar(Cine cine) throws DAOExcepcion {
		try {
			getHibernateTemplate().save(cine);
		    getHibernateTemplate().flush();
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		return cine;
	}

	@Override
	public Cine modificar(Cine cine) throws DAOExcepcion {
		try {
			getHibernateTemplate().update(cine);
		    getHibernateTemplate().flush();
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		return cine;
	}

	@Override
	public Cine eliminar(Cine cine) throws DAOExcepcion {
		try {
			getHibernateTemplate().delete(cine);
		    getHibernateTemplate().flush();
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		return cine;
	}

	@Override
	public Cine obtener(int idCine) throws DAOExcepcion {
		Cine cine = new Cine();
		try {
			cine = (Cine)getHibernateTemplate().find("from Cine where idCine = ?",
													idCine).get(0);
		} catch (Exception e) {

			throw new DAOExcepcion(e.getMessage());
		}
		return cine;
	}

}
